<template>
  <div v-loading="loading" style="display: flex; flex-direction: column; flex: 1" element-loading-text="加载中...">
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addData"> 添加模块 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div class="search flex-align-center">
        <el-select v-model="type" class="input-with mr5" placeholder="请选择模块类型" filterable clearable @change="getList">
          <el-option value="1" label="安装" />
          <el-option value="2" label="维修" />
          <el-option value="3" label="保养" />
          <el-option value="4" label="其他" />
        </el-select>
        <el-input v-model="name" placeholder="名称搜索" class="input-with mr5" clearable @keyup.enter="getList"
          @clear="getList" />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <div class="table-list">
      <el-table border stripe resizable :data="tableData" @selection-change="handleChange" ref="tableDom" height="100%"
        style="position: absolute">
        <!-- 选择 -->
        <el-table-column type="selection" width="50" fixed="left" />

        <!-- 序号 -->
        <el-table-column type="index" label="序号" width="50" />

        <!-- 模块名称 -->
        <el-table-column show-overflow-tooltip prop="name" label="模块名称" min-width="150">
          <template #default="scope">
            <HLink @click="handleModuleNameClick(scope.row.id)">
              {{ scope.row.name }}
            </HLink>
          </template>
        </el-table-column>

        <!-- 模块类型 -->
        <el-table-column prop="type" label="模块类型" width="74">
          <template #default="scope">
            <span v-if="scope.row.type == 1">安装</span>
            <span v-if="scope.row.type == 2">维修</span>
            <span v-if="scope.row.type == 3">保养</span>
            <span v-if="scope.row.type == 4">其他</span>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="!scope.row.status">启用</HStatus>
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
          </template>
        </el-table-column>

        <!-- 质保状态 -->
        <el-table-column prop="overinsured" label="质保状态" width="74">
          <template #default="scope">
            <span v-if="!scope.row.overinsured">保内</span>
            <span v-if="scope.row.overinsured">保外</span>
          </template>
        </el-table-column>

        <!-- 保内费用 -->
        <el-table-column show-overflow-tooltip prop="inSourcingPrice" label="保内费用" width="100" align="right">
          <template #default="scope">
            <span>￥{{ scope.row.inSourcingPrice }}</span>
          </template>
        </el-table-column>

        <!-- 保外费用 -->
        <el-table-column show-overflow-tooltip prop="outSourcingPrice" label="保外费用" width="100" align="right">
          <template #default="scope">
            <span>￥{{ scope.row.outSourcingPrice }}</span>
          </template>
        </el-table-column>
        <!-- 商品单价 -->
        <el-table-column show-overflow-tooltip prop="collectCustomerGoodsPrice" label="商品单价" width="100" align="right">
          <template #default="scope">
            <span>￥{{ scope.row.collectCustomerGoodsPrice }}</span>
          </template>
        </el-table-column>
        
        <!-- 移动端报单可见 -->
        <el-table-column show-overflow-tooltip prop="mobileCreateOrderShow" label="移动端报单可见" width="110">
          <template #default="scope">
            <span v-if="scope.row.mobileCreateOrderShow">显示</span>
            <span v-else>隐藏</span>
          </template>
        </el-table-column>

        <!-- 质保工单 -->
        <el-table-column show-overflow-tooltip prop="enableWarrantyOrder" label="质保工单" width="74">
          <template #default="scope">
            <span v-if="scope.row.enableWarrantyOrder">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>

        <!-- 质保周期 -->
        <el-table-column show-overflow-tooltip prop="warrantyDay" label="质保周期" width="74" align="right">
          <template #default="scope">
            <span>{{ scope.row.warrantyDay }}天</span>
          </template>
        </el-table-column>

        <!-- 拨打电话类型 -->
        <el-table-column show-overflow-tooltip prop="callPhoneType" label="拨打电话类型" width="100">
          <template #default="scope">
            <span v-if="scope.row.callPhoneType === 0">关闭</span>
            <span v-else>必须拨打</span>
          </template>
        </el-table-column>

        <!-- 结单核销码 -->
        <el-table-column show-overflow-tooltip prop="enableStatementVerifCode" label="结单核销码" width="86">
          <template #default="scope">
            <span v-if="scope.row.enableStatementVerifCode">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>

        <!-- 结单核销码类型 -->
        <el-table-column label="结单核销码类型" prop="statementVerifCodeType" width="110">
          <template #default="scope">
            {{ scope.row.statementVerifCodeType == 1 ? '随机' : '固定' }}
          </template>
        </el-table-column>

        <!-- 分配客服 -->
        <el-table-column label="分配客服" prop="autoDispatchClient" width="130">
          <template #default="scope">
            <span v-if="scope.row.autoDispatchClient">按规则自动分配</span>
            <span v-else type="info">客服人工分配</span>
          </template>
        </el-table-column>

        <!-- 分配客服规则 -->
        <el-table-column show-overflow-tooltip label="分配客服规则" prop="workClientStrategy" width="150" />

        <!-- 分派服务商 -->
        <el-table-column label="分派服务商" prop="autoDispatchNetwork" width="130">
          <template #default="scope">
            <span v-if="scope.row.autoDispatchNetwork">按规则自动派单</span>
            <span v-else type="info">服务商人工分派</span>
          </template>
        </el-table-column>

        <!-- 预约时间 -->
        <el-table-column prop="reservationTimeType" label="预约时间" width="100">
          <template #default="scope">
            <span v-if="scope.row.reservationTimeType == 1">不启用</span>
            <span v-if="scope.row.reservationTimeType == 2">24小时</span>
            <span v-if="scope.row.reservationTimeType == 3">预约时间范围</span>
          </template>
        </el-table-column>

        <!-- 报单路径 -->
        <el-table-column show-overflow-tooltip prop="path" label="报单路径" width="400" />

        <!-- 创建时间 -->
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

        <!-- 更新时间 -->
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink @click="handleEditModule(scope.row.id)">编辑</HLink>
              <HLink @click="handleDelete(scope.row.id)">删除</HLink>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <EditOrModuleModal :mode="modalMode" :title="modalTitle" :module-id="currentEditModuleId" :loading="dialogLoading"
      :visible="modalVisible" @delete="changeStatus(4)" @close="modalVisible = false" @updated="getList" />

    <!-- 分页 -->
    <div class="footer flex-justify-end">
      <Pagination ref="pagination" :list_total="total" @size-change="getList" @current-change="getList" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, markRaw, h } from 'vue'
import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import EditOrModuleModal from './EditOrModuleModal.vue'
import { useRouter } from 'vue-router'
import { moduleGetList, moduleDisable, moduleDelete } from '@/api/basic'
import { OrderModule } from './types'
import HPlainButton from '@/components/common/button/HPlainButton.vue'
import HButton from '@/components/common/button/HButton.vue'
import HStatus from '@/components/common/status/HStatus.vue'
import HLink from '@/components/common/link/HLink.vue'

// 间距组件的间隔符
const spacer = h(ElDivider, {
  direction: 'vertical',
  style: 'display: flex; align-items: center;',
})

const router = useRouter()
const loading = ref(false)
const name = ref('') // 关键词
const type = ref('') // 模块类型

const tableData = ref<Array<OrderModule>>([]) // 列表数据
const tableDom = ref() // 列表dom

const pagination = ref() // 分页dom
const total = ref(0) // 总数目

// 当前编辑的模块的ID
const currentEditModuleId = ref('-1')

// 获取分页数据
const getPageData = () => {
  return {
    limit: pagination.value.size,
    name: name.value,
    page: pagination.value.current,
    type: type.value,
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  const res = await moduleGetList(getPageData())
  loading.value = false
  tableData.value = res.data.data.rows
  total.value = parseInt(res.data.data.total)
}

// 获取表格选中的数据
const selecttion = ref([])

// 弹窗模式：edit-编辑，add-添加
const modalMode = ref<'edit' | 'add'>('edit')

// 弹窗加载状态
const dialogLoading = ref(false)

// 弹窗标题
const modalTitle = ref('编辑模块')

// 弹窗的显示状态
const modalVisible = ref(false)

const handleChange = (val: any[]) => {
  if (val.length != 0) {
    val.forEach((item: { id: any }) => {
      if (Object.values(selecttion.value).indexOf(item.id) == -1) {
        selecttion.value.push(item.id)
      } else {
        selecttion.value = selecttion.value.filter((i) => i == item.id)
      }
    })
  } else {
    selecttion.value = []
  }
}

// 添加模块
const addData = () => {
  modalMode.value = 'add'
  modalTitle.value = '添加模块'
  modalVisible.value = true
}

// 编辑模块
const handleEditModule = (id: string) => {
  modalMode.value = 'edit'
  currentEditModuleId.value = id
  modalTitle.value = '编辑模块'
  modalVisible.value = true
}

// 模块名称点击事件
const handleModuleNameClick = (id: string) => {
  router.push('/busic/base/moduleDetail/' + id)
}

// 修改状态方法
const changeMethod = (type, method, arr, status, dialog) => {
  if (arr.length == 0) {
    ElMessage({
      message: `请选择要${type}的模块`,
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    type: type == '删除' ? 'error' : 'warning',
    title: '提示',
    icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
    message: `确认${type}选中的模块?`,
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    draggable: true,
    autofocus: false,
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 1000)
      } else {
        done()
      }
    },
  }).then(async () => {
    if (status != 3) {
      const res = await method(arr, status)
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
    } else {
      const res = await method(arr)
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        return
      }
      if (dialog != '') {
        modalVisible.value = false
      }
    }
    selecttion.value = []
    tableDom.value.clearSelection()
    getList()
  })
}

// 批量启用/禁用/删除
const changeStatus = (n) => {
  if (n == 1) {
    changeMethod('启用', moduleDisable, selecttion.value, false, '')
  }
  if (n == 2) {
    changeMethod('禁用', moduleDisable, selecttion.value, true, '')
  }
  if (n == 3) {
    changeMethod('删除', moduleDelete, selecttion.value, 3, '')
  }
  if (n == 4) {
    changeMethod('删除', moduleDelete, [currentEditModuleId.value], 3, modalVisible)
  }
}

// 删除事件
const handleDelete = (id: number) => {
  ElMessageBox({
    type: 'error',
    title: '提示',
    icon: markRaw(Delete),
    message: '确认删除该模块?',
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    autofocus: false,
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        moduleDelete([id]).then((res) => {
          instance.confirmButtonLoading = false
          if (res.data.success == true) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 2000,
            })
            instance.confirmButtonText = '确定'
            done()
            getList()
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'warning',
                duration: 2000,
              })
            instance.confirmButtonText = '确定'
            done()
          }
        })
      } else {
        done()
      }
    },
  })
}

defineExpose({ getList })
</script>

<style scoped lang="scss">
@import '../../index.scss';
</style>
